'use strict';
app.controller('shopHistoryCtrl',[ '$scope','$filter','$modal','shopAnalysisService','utilService','toaster',function($scope,$filter,$modal,shopAnalysisService,utilService,toaster) {
    $scope.start=new Date(new Date().setHours(0,0,0,0)-1000*60*60*24);
    $scope.end=new Date(new Date().setHours(23,59,59,999)-1000*60*60*24);
    $scope.analysis={
        startTime:$filter('date')($scope.start,'yyyy-MM-dd'),
        endTime:$filter('date')($scope.end,'yyyy-MM-dd')
    };

    //查询店铺分析数据
    $scope.query=function(){
        $scope.analysis.startTime=$filter('date')( $scope.analysis.startTime,'yyyy-MM-dd');
        $scope.analysis.endTime=$filter('date')($scope.analysis.endTime,'yyyy-MM-dd');
        shopAnalysisService.findShopAnalysis($scope).then(function(result){
            switch (result.status){
                case 200:
                    $scope.analysisData=result.data;
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        });
    }

    //导出店铺分析数据
    $scope.exportData=function(){
        openModal("确定要导出已查询出的记录吗？" +
            "(导出时间跟导出数据量的大小有关，请耐心等待)");
        function openModal(msg){
            utilService.modal($modal, $scope, {
                title:"温馨提示",
                controller:"exportShopAnalysisCtrl",
                message:msg,
                data: $scope.analysis
            });
        }
    }

    //查询出指定时间内不同性别的买家数量
    $scope.querySex=function(){
        shopAnalysisService.querySex($scope).then(function(result){
            switch (result.status){
                case 200:
                    $scope.data = [
                        {value:result.data.man, name:'男性'},
                        {value:result.data.woman, name:'女性'},
                        {value:result.data.unknown, name:'未知'}
                    ];
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        });
    }

    $scope.fun=function(){
        $scope.query();
        $scope.querySex();
    }
    $scope.fun();

    $scope.legend = ["男性","女性","未知"];
    $scope.data = [
        {value:0, name:'男性'},
        {value:0, name:'女性'},
        {value:0, name:'未知'}
    ];
    //查询连锁品牌下店铺列表
    $scope.getShopList=function(){
        shopAnalysisService.getShopList($scope).then(
            function(rlt){
                switch (rlt.status){
                    case 200:
                        $scope.shopList=rlt.data;
                        break;
                    default :
                        toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                        break;
                }
            }
        );
    };
    $scope.getShopList();
}]);

//导出店铺分析数据模态框Controller
app.controller('exportShopAnalysisCtrl', ['$scope', '$modalInstance','modalData','shopAnalysisService','$filter',
    function($scope, $modalInstance,modalData,shopAnalysisService,$filter) {
        $scope.modal = modalData;
        $scope.param = modalData.data;
        $scope.param.startTime=$filter('date')( $scope.param.startTime,'yyyy-MM-dd');
        $scope.param.endTime=$filter('date')( $scope.param.endTime,'yyyy-MM-dd');
        $scope.AllowToReport=true;
        $scope.ok=function(){
            if(!$scope.AllowToReport){
                return;
            }
            $scope.AllowToReport=false;
            shopAnalysisService.exportData($scope);
            $modalInstance.dismiss('success');
        }
        //取消弹窗
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    }
]);

app.controller('shop_page_ctrl', function($scope) {
    $scope.legend = ["其他","店铺页面","商品页面"];
    $scope.item = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30'];
    $scope.data = [
        {value:335, name:'其他'},
        {value:310, name:'店铺页面'},
        {value:234, name:'商品页面'}
    ];
});

app.directive('pie', function() {
    return {
        scope: {
            id: "@",
            legend: "=",
            item: "=",
            data: "="
        },
        restrict: 'E',
        template: '<div style="height:250px;"></div>',
        replace: true,
        link: function($scope, element, attrs, controller) {
            var option = {
                tooltip : {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend: {
                    orient : 'vertical',
                    x : 'left',
                    data:$scope.legend
                },
                toolbox: {
                    show : true,
                    feature : {
                        magicType : {
                            show: true,
                            type: ['pie', 'funnel'],
                            option: {
                                funnel: {
                                    x: '25%',
                                    width: '50%',
                                    funnelAlign: 'center',
                                    max: 1548
                                }
                            }
                        },
                        saveAsImage : {show: true}
                    }
                },
                calculable : true,
                series : [
                    {
                        name:'买家性别',
                        type:'pie',
                        radius : ['50%', '70%'],
                        itemStyle : {
                            normal : {
                                label : {
                                    show : true
                                },
                                labelLine : {
                                    show : true
                                }
                            },
                            emphasis : {
                                label : {
                                    show : false,
                                    position : 'center',
                                    textStyle : {
                                        fontSize : '30',
                                        fontWeight : 'bold'
                                    }
                                }
                            }
                        },
                        data:$scope.data

                    }
                ]
            };

            var myChart = echarts.init(document.getElementById($scope.id),'macarons');
            myChart.setOption(option);

            $scope.$watch('data',function(data){
                var serie=[{
                    name:'买家性别',
                    type:'pie',
                    radius : ['50%', '70%'],
                    itemStyle : {
                        normal : {
                            label : {
                                show : true
                            },
                            labelLine : {
                                show : true
                            }
                        },
                        emphasis : {
                            label : {
                                show : false,
                                position : 'center',
                                textStyle : {
                                    fontSize : '30',
                                    fontWeight : 'bold'
                                }
                            }
                        }
                    },
                    data:data
                }];
                option.series=serie;
                myChart.clear();
                myChart.setOption(option,true);
            })
        }
    };
});

function getPreMonth(date,num) {
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中月的天数
    var year2 = year;
    var month2=parseInt(month);

    for(var i=0;i<num;i++){
        month2 = parseInt(month2) - 1;
        if (month2 == 0) {
            year2 = parseInt(year2) - 1;
            month2 = 12;
        }
    }

    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
}

//app.directive('pre', function() {
//    return {
//        scope: {
//            id: "@",
//            legend: "=",
//            item: "=",
//            data: "="
//        },
//        restrict: 'E',
//        template: '<div style="height:250px;"></div>',
//        replace: true,
//        link: function($scope, element, attrs, controller) {
//            var option = {
//                title : {
//                    text: '2011全国GDP（亿元）',
//                    subtext: '数据来自国家统计局'
//                },
//                tooltip : {
//                    trigger: 'item'
//                },
//                legend: {
//                    x:'right',
//                    selectedMode:false,
//                    data:['北京','上海','广东']
//                },
//                dataRange: {
//                    orient: 'horizontal',
//                    min: 0,
//                    max: 55000,
//                    text:['高','低'],           // 文本，默认为数值文本
//                    splitNumber:0
//                },
//                toolbox: {
//                    show : true,
//                    orient: 'vertical',
//                    x:'right',
//                    y:'center',
//                    feature : {
//                        mark : {show: true},
//                        dataView : {show: true, readOnly: false}
//                    }
//                },
//                series : [
//                    {
//                        name: '2011全国GDP分布',
//                        type: 'map',
//                        mapType: 'china',
//                        mapLocation: {
//                            x: 'left'
//                        },
//                        selectedMode : 'multiple',
//                        itemStyle:{
//                            normal:{label:{show:true}},
//                            emphasis:{label:{show:true}}
//                        },
//                        data:[
//                            {name:'西藏', value:605.83},
//                            {name:'青海', value:1670.44},
//                            {name:'宁夏', value:2102.21},
//                            {name:'海南', value:2522.66},
//                            {name:'甘肃', value:5020.37},
//                            {name:'贵州', value:5701.84},
//                            {name:'新疆', value:6610.05},
//                            {name:'云南', value:8893.12},
//                            {name:'重庆', value:10011.37},
//                            {name:'吉林', value:10568.83},
//                            {name:'山西', value:11237.55},
//                            {name:'天津', value:11307.28},
//                            {name:'江西', value:11702.82},
//                            {name:'广西', value:11720.87},
//                            {name:'陕西', value:12512.3},
//                            {name:'黑龙江', value:12582},
//                            {name:'内蒙古', value:14359.88},
//                            {name:'安徽', value:15300.65},
//                            {name:'北京', value:16251.93, selected:true},
//                            {name:'福建', value:17560.18},
//                            {name:'上海', value:19195.69, selected:true},
//                            {name:'湖北', value:19632.26},
//                            {name:'湖南', value:19669.56},
//                            {name:'四川', value:21026.68},
//                            {name:'辽宁', value:22226.7},
//                            {name:'河北', value:24515.76},
//                            {name:'河南', value:26931.03},
//                            {name:'浙江', value:32318.85},
//                            {name:'山东', value:45361.85},
//                            {name:'江苏', value:49110.27},
//                            {name:'广东', value:53210.28, selected:true}
//                        ]
//                    },
//                    {
//                        name:'2011全国GDP对比',
//                        type:'pie',
//                        roseType : 'area',
//                        tooltip: {
//                            trigger: 'item',
//                            formatter: "{a} <br/>{b} : {c} ({d}%)"
//                        },
//                        center: [document.getElementById('main').offsetWidth - 250, 225],
//                        radius: [30, 120],
//                        data:[
//                            {name: '北京', value: 16251.93},
//                            {name: '上海', value: 19195.69},
//                            {name: '广东', value: 53210.28}
//                        ]
//                    }
//                ],
//                animation: false
//            };
//            var ecConfig = require('echarts/config');
//            myChart.on(ecConfig.EVENT.MAP_SELECTED, function (param){
//                var selected = param.selected;
//                var mapSeries = option.series[0];
//                var data = [];
//                var legendData = [];
//                var name;
//                for (var p = 0, len = mapSeries.data.length; p < len; p++) {
//                    name = mapSeries.data[p].name;
//                    //mapSeries.data[p].selected = selected[name];
//                    if (selected[name]) {
//                        data.push({
//                            name: name,
//                            value: mapSeries.data[p].value
//                        });
//                        legendData.push(name);
//                    }
//                }
//                option.legend.data = legendData;
//                option.series[1].data = data;
//                myChart.setOption(option, true);
//            })
//        }
//    };
//});